#!/bin/bash

export LANG=en_US.UTF-8
export JAVA_HOME=/opt/jre
export PATH=$JAVA_HOME/bin:$PATH
LOG_PATH="/var/log/monitor"
LOG_NAME="kafka"
INTERVAL=60
KAFKA_ROOT="/opt/kafka"
KAFKA_SERVERS="10.0.4.104:9092,10.0.4.105:9092,10.0.4.106:9092"

function Init {
    local self_count=$(pgrep -cx "$(basename $0)")
    [ 0 -eq $? ] || exit 1
    [ 1 -eq $self_count ] || exit 1
    mkdir -p $LOG_PATH || exit 1
}

function Log {
    local msg="$1"
    local log_time="$(date +'%F %T')"
    local log_file="$LOG_PATH/$LOG_NAME-${log_time% *}.log"
    echo "$log_time $msg" >> $log_file
    cd $LOG_PATH && ls ${LOG_NAME}-* 2>/dev/null \
        | head -n -7 | xargs rm -f
}

function GetKafkaInfo {
    local consumer_group=
    cd $KAFKA_ROOT/bin || return 1
    for consumer_group in $(./kafka-consumer-groups.sh \
        --bootstrap-server $KAFKA_SERVERS --list); do
        ./kafka-consumer-groups.sh \
            --bootstrap-server $KAFKA_SERVERS \
            --group $consumer_group --describe \
            | tail -n +3 | awk '$7 !~ /^-$/{print $1,$2,
                $3,$4,$5,substr($7,2),"'$consumer_group'"}'
    done
}

function Main {
    sleep $INTERVAL
    GetKafkaInfo|while read line; do
        Log "$line"
    done
}

# start
Init
Main

